package logic

import (
	"msems/dao/mysql"
	"msems/models"
	"msems/pkg/email"
	"msems/pkg/jwt"

	"go.uber.org/zap"
)

// SignUp 注册逻辑
func SignUp(p *models.ParamSignUp) (err error) {
	// 1.判断用户是否存在
	err = mysql.CheckUserExist(p.Username)
	if err != nil {
		// 查询出错
		return err
	}

	// 2.生成UID
	// 构造user实例
	user := &models.User{
		Username: p.Username,
		Password: p.Password,
	}
	// 3.加密并保存进数据库
	return mysql.InsertUser(user)
}

// AdminLogin 登录逻辑
func AdminLogin(p *models.ParamLogin) (user *models.User, err error) {
	// 构造user实例
	user = &models.User{
		Username: p.Username,
		Password: p.Password,
	}
	//1. 验证用户 传递的是指针 可以拿到user_id
	if err = mysql.AdminLoginUser(user); err != nil {
		zap.L().Error("login.login failed", zap.String("username", p.Username), zap.Error(err))
		return nil, err
	}
	// 生成jwt(内容在pkg->jwt>jwt.go) 返回aToken和rToken
	token, err := jwt.GenToken(user.UserID, user.Username)
	if err != nil {
		return
	}
	user.Token = token
	return
}

// AdminSendEmail 判断以及发送修改密码验证码
func AdminSendEmail(p *models.AdminEmail) (err error) {
	user := new(models.User)
	// 验证用户名和邮箱
	err = mysql.AdminSendEmail(p, user)
	if err != nil {
		return err
	}
	var code string
	//生成四位数的验证码并放入数据库
	code, err = mysql.EmailCode(user.Email, p.Username)
	if err != nil {
		return err
	}
	//发送邮件
	err = email.SendEmailToUser(user.Email, code)
	if err != nil {
		return err
	}
	return
}

// AdminCode 验证用户输入的验证码
func AdminCode(p *models.AdminCode) (err error) {
	//验证用户名和验证码
	err = mysql.AdminCode(p)
	if err != nil {
		return err
	}
	return
}

// AdminChangeP 修改密码
func AdminChangeP(p *models.ParamSignUp) (err error) {
	return mysql.AdminChangeP(p)
}

// AdminSignUp 注册逻辑
func AdminSignUp(p *models.ParamSignUp, id int64) (err error) {
	// 1.判断用户是否存在
	err = mysql.CheckUserExist(p.Username)
	if err != nil {
		// 查询出错
		return err
	}

	// 2.生成UID
	// 构造user实例
	user := &models.User{
		Username:  p.Username,
		Password:  p.Password,
		Email:     p.Email,
		ClassID:   p.ClassID,
		TeacherID: p.TeacherID,
		CollegeID: p.CollegeID,
		Level:     p.LeveL,
	}
	// 3.加密并保存进数据库
	err = mysql.AdminInsertUser(user)
	if err != nil {
		return
	}
	//记录日志
	return AdminLog(id, StringInsert, p.Username)
}
